package com.bestom.hardwaretest.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import com.bestom.hardwaretest.R;
import com.bestom.hardwaretest.util.ToastUtil;
import com.suke.widget.SwitchButton;
import java.util.ArrayList;
import java.util.List;

public class WiFiActivity extends BaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_wifi);
        initData();
        initView();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        //="android.net.wifi.STATE_CHANGE"  监听wifi状态的变化
        registerReceiver(mReceiver, filter);
    }

    private WifiManager mWifiManager;
    private WifiAdapter mWifiAdapter;

    private void initData() {
        mWifiList = new ArrayList();
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiAdapter = new WifiAdapter(this,mWifiList);
    }

    private ListView mListView;
    private List<ScanResult> mWifiList;
    public int level;

    private void initView() {
        findViewById(R.id.back).setOnClickListener(v -> finish());
        SwitchButton wifi = findViewById(R.id.wifi);
        wifi.setOnCheckedChangeListener((view, isChecked) -> {
            if (isChecked) open();
            else close();
        });

        mListView = findViewById(R.id.wifi_list);
        mListView.setAdapter(mWifiAdapter);
        mListView.setOnItemClickListener((parent, view, position, id) -> {
            int margin = (int) (20 * Resources.getSystem().getDisplayMetrics().density);
            AlertDialog.Builder alert = new AlertDialog.Builder(WiFiActivity.this);
            String ssid = mWifiList.get(position).SSID;
            alert.setTitle(ssid);
            alert.setMessage("输入密码");
            final EditText etPassword = new EditText(WiFiActivity.this);
            final SharedPreferences preferences = getSharedPreferences("wifi_password", Context.MODE_PRIVATE);
            etPassword.setText(preferences.getString(ssid, ""));
            alert.setView(etPassword, margin, 0, margin, 0);
            //alert.setView(view1);
            alert.setPositiveButton("连接", (dialog, which) -> {
                String pw = etPassword.getText().toString();
                if (pw.length() < 8) {
                    ToastUtil.toast("密码至少8位");
                    return;
                }
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString(ssid, pw);   //保存密码
                editor.apply();
                addNetwork(createWifiInfo(ssid, etPassword.getText().toString(), 3));
                ToastUtil.toast("正在连接 "+ssid+" 请稍后...");
            });
            alert.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
            alert.create();
            alert.show();
        });

        if(mWifiManager.isWifiEnabled()) {
            wifi.setChecked(true);
            startScan();
        }
    }

    public WifiConfiguration createWifiInfo(String ssId, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssId + "\"";

        WifiConfiguration tempConfig = isExist(ssId);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        // WIFICIPHER_NOPASS
        if (Type == 1) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // WIFICIPHER_WEP
        if (Type == 2) {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        // WIFICIPHER_WPA
        if (Type == 3) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }
    private WifiConfiguration isExist(String ssId) {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\""+ssId+"\"")) {
                return existingConfig;
            }
        }
        return null;
    }
    public void addNetwork(WifiConfiguration wcg) {
        int wcgId = mWifiManager.addNetwork(wcg);
        mWifiManager.enableNetwork(wcgId, true);
    }

    public class WifiAdapter extends BaseAdapter {
        LayoutInflater inflater;
        List<ScanResult> list;

        public WifiAdapter(Context context, List<ScanResult> list) {
            this.inflater = LayoutInflater.from(context);
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint({"ViewHolder", "InflateParams"})
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            view = inflater.inflate(R.layout.wifi_listitem, null);
            ScanResult scanResult = list.get(position);
            TextView wifiSsId = view.findViewById(R.id.ssid);
            ImageView wifiLevel = view.findViewById(R.id.wifi_level);
            ImageView lock = view.findViewById(R.id.lock);
            wifiSsId.setText(scanResult.SSID);
            level = WifiManager.calculateSignalLevel(scanResult.level, 5);
            if (scanResult.capabilities.contains("WEP") || scanResult.capabilities.contains("PSK") ||
                    scanResult.capabilities.contains("EAP")) {
                lock.setImageResource(R.drawable.lock);
            }
            //判断信号强度，显示对应的指示图标
            if (level == 0) wifiLevel.setImageResource(R.drawable.wifi_0);
            else if (level == 1) wifiLevel.setImageResource(R.drawable.wifi_1);
            else if (level == 2) wifiLevel.setImageResource(R.drawable.wifi_2);
            else if (level == 3) wifiLevel.setImageResource(R.drawable.wifi_3);
            else if (level == 4) wifiLevel.setImageResource(R.drawable.wifi_4);
            return view;
        }
    }

    //监听wifi状态
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            final String action = intent.getAction();
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                // wifi已成功扫描到可用wifi。
                //得到扫描结果
                List<ScanResult> results = mWifiManager.getScanResults();
                // 得到配置好的网络连接
                if (results == null) {
                    if (mWifiManager.getWifiState() == 3) {
                        ToastUtil.toast("当前区域没有无线网络!");
                    } else if (mWifiManager.getWifiState() == 2) {
                        ToastUtil.toast("wifi正在开启，请稍后扫描!");
                    } else {
                        ToastUtil.toast("WiFi没有开启");
                    }
                } else {
                    for (ScanResult result : results) {
                        Log.d("ScanResult","ScanResult--->" + result.SSID);
                        if (result.SSID == null || result.SSID.length() == 0 || result.capabilities.contains("[IBSS]")) {
                            continue;
                        }
                        boolean found = false;
                        for (ScanResult item : mWifiList) {
                            if (item.SSID.equals(result.SSID) && item.capabilities.equals(result.capabilities)) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            mWifiList.add(result);
                            mWifiAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
                NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (wifiInfo.isConnected()) {
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    String ssId = wifiManager.getConnectionInfo().getSSID();
                    ToastUtil.toast(ssId + "  连接成功!");
                }
            }
        }
    };

    private void close() {
        if(mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
        mWifiList.clear();
        mWifiAdapter.notifyDataSetChanged();
    }

    private void open() {
        if (!mWifiManager.isWifiEnabled()) {
            //开启wifi
            mWifiManager.setWifiEnabled(true);
            ToastUtil.toast("为您打开WIFI中...");
        }
        ToastUtil.toast("正在搜索可用WIFI，请稍后...");
        startScan();
    }

    public void startScan() {
        mWifiManager.startScan();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }
}
